package com.trace.app.config.fabric;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hyperledger.fabric.gateway.Gateway;
import org.hyperledger.fabric.gateway.Identities;
import org.hyperledger.fabric.gateway.Wallet;
import org.hyperledger.fabric.gateway.Wallets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;

import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;

@Configuration
@AllArgsConstructor
@Slf4j
public class HyperLedgerFabricGatewayConfig {

    final HyperLedgerFabricProperties hyperLedgerFabricProperties;

    @Autowired
    private ResourceLoader resourceLoader;

    @Bean
    public Gateway gateway() throws Exception {
        //Path privateKeyPath = Paths.get(resourceLoader.getResource(hyperLedgerFabricProperties.getPrivateKeyPath()).getURI());
        //Path certificatePath = Paths.get(resourceLoader.getResource(hyperLedgerFabricProperties.getCertificatePath()).getURI());


        Path privateKeyPath = Paths.get(resourceLoader.getResource(hyperLedgerFabricProperties.getPrivateKeyPath().replace("\\", "/")).getURI());
        Path certificatePath = Paths.get(resourceLoader.getResource(hyperLedgerFabricProperties.getCertificatePath().replace("\\", "/")).getURI());

        log.error("privateKeyPath:{}", privateKeyPath);
        log.error("certificatePath:{}", certificatePath);

        BufferedReader certificateReader = Files.newBufferedReader(certificatePath, StandardCharsets.UTF_8);
        X509Certificate certificate = Identities.readX509Certificate(certificateReader);

        BufferedReader privateKeyReader = Files.newBufferedReader(Paths.get(resourceLoader.getResource(hyperLedgerFabricProperties.getPrivateKeyPath()).getURI()), StandardCharsets.UTF_8);
        PrivateKey privateKey = Identities.readPrivateKey(privateKeyReader);

        Wallet wallet = Wallets.newInMemoryWallet();
        wallet.put("user1", Identities.newX509Identity(hyperLedgerFabricProperties.getMspId(), certificate, privateKey));


        Gateway.Builder builder = Gateway.createBuilder()
                .identity(wallet, "user1")
                //.networkConfig(Paths.get(hyperLedgerFabricProperties.getNetworkConnectionConfigPath()));
                .networkConfig(Paths.get(resourceLoader.getResource(hyperLedgerFabricProperties.getNetworkConnectionConfigPath()).getURI()));

        Gateway gateway = builder.connect();

        log.info("=========================================== connected fabric gateway {} ", gateway);

        return gateway;
    }

}
